<script setup lang="ts">
import type { DictDataType } from '#/utils/dict';

import { computed, onMounted, ref } from 'vue';

import { dictUtils } from '#/utils/dict';

const props = withDefaults(
  defineProps<{
    icon?: string;
    labelField?: string;
    multiple?: boolean;
    options?: DictDataType[];
    selectable?: boolean;
    type?: string;
    value?: Array<boolean | number | string> | boolean | number | string;
    valueField?: string;
  }>(),
  {
    type: '',
    options: () => [],
    multiple: false,
    selectable: false,
    labelField: 'label',
    valueField: 'value',
    value: '',
    icon: '',
  },
);

const emit = defineEmits(['update:value', 'tag-click']);

const dicts = ref<any>([]);

const selectedValues = ref<Array<number | string>>(
  Array.isArray(props.value) ? props.value : [],
);

// const dicts = computed(() => {
//   return props.type ? dictUtils.getDictOptions(props.type) : props.options;
// });

const dict = computed(() => {
  for (const item of dicts.value) {
    if (`${item[props.valueField]}` === `${props.value}`) {
      return item;
    }
  }
  return {};
});

const handleClick = (dict: DictDataType) => {
  emit('tag-click', dict);
  if (props.selectable) {
    if (props.multiple) {
      const index = selectedValues.value.indexOf(dict.value);
      if (index === -1) {
        selectedValues.value.push(dict.value);
      } else {
        selectedValues.value.splice(index, 1);
      }
      emit('update:value', selectedValues.value);
    } else {
      emit('update:value', dict.value);
    }
  }
};

const getTagColor = (dict: DictDataType) => {
  return (props.multiple && selectedValues.value.includes(dict.value)) ||
    (!props.multiple && props.value == dict.value)
    ? 'blue'
    : '';
};

onMounted(async () => {
  dicts.value = await dictUtils.getDictOptionsAsync(props.type, 'string');
});
</script>

<template>
  <template v-if="props.selectable">
    <div
      v-for="(item, index) in dicts"
      :key="index"
      :class="{ 'cursor-pointer': selectable }"
      @click="handleClick(item)"
    >
      <a-tag :color="getTagColor(item)" :round="!multiple">
        {{ item[labelField] }}
      </a-tag>
    </div>
  </template>
  <div v-else-if="Array.isArray(value)" class="flex flex-row flex-wrap">
    <template v-for="(item, index) in dicts" :key="index">
      <div v-if="selectedValues.includes(item.value)" class="mb-1">
        <a-tag>
          {{ item[labelField] }}
        </a-tag>
      </div>
    </template>
  </div>
  <template v-else>
    <a-tag :color="dict?.colorType || ''">
      {{ (dict && dict[labelField]) || value }}
    </a-tag>
  </template>
</template>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}
</style>
